package org.raymond.icloud.common.core.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.raymond.icloud.common.core.constants.Headers;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
// FeignClientFactoryBean#configureUsingConfiguration
// FeignClientsConfiguration
// @Configuration 有此注解则全局生效,无此注解则只生效于配置的FeignClient
@Configuration
public class FeignConfiguration {

    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                HttpServletRequest request = getHttpServletRequest();
                String contentTypeVal = request.getHeader(Headers.CONTENT_TYPE.getName());
                if(StringUtils.isBlank(contentTypeVal)){
                    contentTypeVal = Headers.CONTENT_TYPE.getValue();
                }
                requestTemplate.header(Headers.CONTENT_TYPE.getName(), contentTypeVal);
                // requestTemplate.header(Headers.CONTENT_LENGTH.getName(), Headers.CONTENT_LENGTH.getValue());
            }

            private HttpServletRequest getHttpServletRequest() {
                try {
                    return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
                } catch (Exception e) {
                    log.error("Get httpServletRequest error: {}", e.getMessage());
                    return null;
                }
            }

            private Map<String, String> getHeaders(HttpServletRequest request) {
                Map<String, String> map = new LinkedHashMap<>();
                Enumeration<String> enumeration = request.getHeaderNames();
                while (enumeration.hasMoreElements()) {
                    String key = enumeration.nextElement();
                    String value = request.getHeader(key);
                    map.put(key, value);
                }
                return map;
            }
        };
    }
}
